﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Data;
using MES.DataGateway.SyncEntity;
using MES.DataGateway.Common;
using MES.DataGateway.SyncInterface;
using MES.DataGateway.StandardEntity;
using MES.DataGateway.OracleDAL;
using MES.DataGateway.SyncCommon;

namespace MES.DataGateway.StandardDataSync
{
    public class Tools : SyncInfterface
    {
        private AssistantClass m_Assistant = new AssistantClass();
        private ServiceEntity m_ServiceInfoEntity = null;
        private string m_ProjectID = "";
        private string m_LibID = "";
        private string m_DataFilePath = "";
        private string m_SyncType = "1";
        private OutInfoEntity m_OutParameterObject = null;
        private List<OutInfoEntity> m_OutParameterObjectList = new List<OutInfoEntity>();
        private string m_AccessoriesPath = "";
        private StandardDAL m_DAL;

        #region 属性
        public string AccessoriesPath
        {
            set { m_AccessoriesPath = value; }
        }

        public OutInfoEntity OutParameterObject
        {
            get { return m_OutParameterObject; }
        }

        public List<OutInfoEntity> OutParameterObjectList
        {
            get { return m_OutParameterObjectList; }
        }

        public ServiceEntity ServiceInfoEntity
        {
            get { return m_ServiceInfoEntity; }
            set { m_ServiceInfoEntity = value; }
        }

        public string ProjectID
        {
            get { return m_ProjectID; }
            set { m_ProjectID = value; }
        }

        public string LibID
        {
            get { return m_LibID; }
            set { m_LibID = value; }
        }

        public string DataFilePath
        {
            get { return m_DataFilePath; }
            set { m_DataFilePath = value; }
        }

        public string SyncType
        {
            get { return m_SyncType; }
            set { m_SyncType = value; }
        }
        #endregion

        public void Execute()
        {
            m_Assistant.DataFilePath = m_DataFilePath;
            m_DAL = new StandardDAL();
            DataTable dt = ReadXML();
            if (dt != null)
                CreateTools(dt);
        }

        private DataTable ReadXML()
        {
            XmlDocument myxml = new XmlDocument();
            myxml.Load(m_DataFilePath);
            DataTable tooldt = new DataTable();
            tooldt.Columns.Add("StepID");
            tooldt.Columns.Add("ToolType");//1,CutTool,2MeasureTool,3SpecialTool
            tooldt.Columns.Add("ToolID");
            tooldt.Columns.Add("ToolName");//编码
            tooldt.Columns.Add("drawingNo");//图号
            tooldt.Columns.Add("Description");//名称
            tooldt.Columns.Add("specNo");//规格
            tooldt.Columns.Add("standardNo");//标准号
            tooldt.Columns.Add("quallity");//数量
            tooldt.Columns.Add("range");//量程
            tooldt.Columns.Add("precision");//精度
            tooldt.Columns["quallity"].DefaultValue = 1;

            XmlNode stu = myxml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/item_id");
            string workFlowItemID = stu.InnerText.Trim();
            stu = myxml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/ly2process_no");
            string workFlowProcessno = stu.InnerText.Trim();
            stu = myxml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/item_revision_id");
            string workFlowRev = stu.InnerText.Trim();

            stu = myxml.SelectSingleNode("/Root/WorkFlow/MEOPs");
            DataSet stepsDS = m_DAL.GetWorkflowStepsByItemID(workFlowItemID, workFlowProcessno, workFlowRev);
            if (stepsDS.Tables[0].Rows.Count == 0)
            {
                return null;
            }
            string stepName = "";
            foreach (XmlNode node in stu.ChildNodes)
            {
                if (node.Name != "MEOP")
                    continue;
                stepName = string.Format("{0}-{1}",
                    node.SelectSingleNode("ly2meop_no").InnerText.Trim(),
                    node.SelectSingleNode("object_name").InnerText.Trim());
                DataRow[] drs = stepsDS.Tables[0].Select(string.Format("WORKFLOWSTEPNAME='{0}'", stepName));
                if (drs.Length == 0)
                    continue;
                stepName = drs[0]["WORKFLOWSTEPID"].ToString();

                string manhours = "";
                XmlNode OPnode = node.SelectSingleNode("spgs_gxgs");
                if (OPnode != null)
                    manhours = OPnode.InnerText.Trim();
                string controlcode = "";
                OPnode = node.SelectSingleNode("ly2control_code");
                if (OPnode != null)
                    controlcode = OPnode.InnerText.Trim();
                UpdateStepInfo(stepName, manhours, controlcode);

                OPnode = node.SelectSingleNode("CutTools");
                if (OPnode.ChildNodes.Count > 0)
                {
                    FillCutTool(tooldt, stepName, OPnode);
                }
                OPnode = node.SelectSingleNode("MeasureTools");
                if (OPnode.ChildNodes.Count > 0)
                {
                    FillMeasureTool(tooldt, stepName, OPnode);
                }
                OPnode = node.SelectSingleNode("SpeToolTools");
                if (OPnode.ChildNodes.Count > 0)
                {
                    FillSpecialTool(tooldt, stepName, OPnode);
                }
                OPnode = node.SelectSingleNode("ChildProcesss/ChildMEOPs");
                if (OPnode == null)
                    continue;
                if (OPnode.ChildNodes.Count > 0)
                {

                    foreach (XmlNode CPOPNode in OPnode.ChildNodes)
                    {
                        if (CPOPNode.Name == "ChildProcess")
                        {
                            workFlowItemID = CPOPNode.SelectSingleNode("item_id").InnerText.Trim();
                            stepsDS = m_DAL.GetWorkflowStepsByItemID(workFlowItemID, "", "");
                            if (stepsDS.Tables[0].Rows.Count == 0)
                            {
                                break;
                            }
                            continue;
                        }
                        if (CPOPNode.Name != "MEOP")
                            continue;
                        if (CPOPNode.ChildNodes.Count == 0)
                        { continue; }
                        stepName = string.Format("{0}-{1}",
                        CPOPNode.SelectSingleNode("ly2meop_no").InnerText.Trim(),
                        CPOPNode.SelectSingleNode("object_name").InnerText.Trim());
                        drs = stepsDS.Tables[0].Select(string.Format("WORKFLOWSTEPNAME='{0}'", stepName));
                        if (drs.Length == 0)
                            continue;
                        stepName = drs[0]["WORKFLOWSTEPID"].ToString();

                        XmlNode COPnode = CPOPNode.SelectSingleNode("CutTools");
                        if (COPnode.ChildNodes.Count > 0)
                        {
                            FillCutTool(tooldt, stepName, COPnode);
                        }
                        COPnode = CPOPNode.SelectSingleNode("MeasureTools");
                        if (COPnode.ChildNodes.Count > 0)
                        {
                            FillMeasureTool(tooldt, stepName, COPnode);
                        }
                        COPnode = CPOPNode.SelectSingleNode("SpeToolTools");
                        if (COPnode.ChildNodes.Count > 0)
                        {
                            FillSpecialTool(tooldt, stepName, COPnode);
                        }

                    }

                }
            }
            return tooldt;
        }

        private static void FillCutTool(DataTable tooldt, string stepName, XmlNode OPnode)
        {
            foreach (XmlNode _node in OPnode.ChildNodes)
            {
                if (_node.Name != "CutTool")
                    continue;
                string code = _node.SelectSingleNode("code").InnerText.Trim();
                if (string.IsNullOrEmpty(code))
                    continue;
                DataRow dr = tooldt.NewRow();
                dr["StepID"] = stepName;
                dr["ToolType"] = 1;
                dr["ToolName"] = code;
                dr["drawingNo"] = _node.SelectSingleNode("drawingNo").InnerText.Trim();
                dr["Description"] = _node.SelectSingleNode("name").InnerText.Trim();
                dr["specNo"] = _node.SelectSingleNode("specNo").InnerText.Trim();
                dr["standardNo"] = _node.SelectSingleNode("standardNo").InnerText.Trim();
                dr["quallity"] = _node.SelectSingleNode("quallity").InnerText.Trim();
                tooldt.Rows.Add(dr);
            }
        }

        private static void FillMeasureTool(DataTable tooldt, string stepName, XmlNode OPnode)
        {
            foreach (XmlNode _node in OPnode.ChildNodes)
            {
                if (_node.Name != "MeasureTool")
                    continue;
                string code = _node.SelectSingleNode("code").InnerText.Trim();
                if (string.IsNullOrEmpty(code))
                    continue;
                DataRow dr = tooldt.NewRow();
                dr["StepID"] = stepName;
                dr["ToolType"] = 2;
                dr["ToolName"] = code;
                dr["drawingNo"] = _node.SelectSingleNode("drawingNo").InnerText.Trim();
                dr["Description"] = _node.SelectSingleNode("name").InnerText.Trim();
                dr["specNo"] = _node.SelectSingleNode("specNo").InnerText.Trim();
                dr["range"] = _node.SelectSingleNode("range").InnerText.Trim();
                dr["precision"] = _node.SelectSingleNode("precision").InnerText.Trim();
                dr["standardNo"] = _node.SelectSingleNode("standardNo").InnerText.Trim();
                dr["quallity"] = _node.SelectSingleNode("quallity").InnerText.Trim();
                tooldt.Rows.Add(dr);
            }
        }

        private static void FillSpecialTool(DataTable tooldt, string stepName, XmlNode OPnode)
        {
            foreach (XmlNode _node in OPnode.ChildNodes)
            {
                if (_node.Name != "SpecialTool")
                    continue;
                string code = _node.SelectSingleNode("code").InnerText.Trim();
                if (string.IsNullOrEmpty(code))
                    continue;
                DataRow dr = tooldt.NewRow();
                dr["StepID"] = stepName;
                dr["ToolType"] = 3;
                dr["ToolName"] = code;
                dr["drawingNo"] = _node.SelectSingleNode("drawingNo").InnerText.Trim();
                if (_node.SelectSingleNode("quantity")!=null)//ad:Wangjh 20230210
                    dr["quallity"] = _node.SelectSingleNode("quantity").InnerText.Trim();

                tooldt.Rows.Add(dr);
            }
        }

        private void CreateTools(DataTable toolDT)
        {
            DataView dv = toolDT.DefaultView;
            DataTable stepdt = dv.ToTable("StepID");
            foreach (DataRow stepdr in stepdt.Rows)
            {
                DataRow[] drs = toolDT.Select(string.Format("StepID='{0}'", stepdr["StepID"]));
                if (drs.Length == 0)
                    continue;
                m_DAL.ClearWorkFlowStepTool(stepdr["StepID"].ToString());
                for (int i = 1; i <= drs.Length; i++)
                {
                    DataRow dr = drs[i - 1];
                    string toolID = "";
                    int toolType = Int32.Parse(dr["ToolType"].ToString());
                    switch (toolType)
                    {
                        case 1:
                            toolID = CreateCutTool(dr);
                            break;
                        case 2:
                            toolID = CreateMeasureTool(dr);
                            break;
                        case 3:
                            toolID = CreateSpecialTool(dr);
                            break;
                    }
                    if (string.IsNullOrEmpty(toolID))
                        continue;
                    int qty = 0;
                    Int32.TryParse(dr["quallity"].ToString(), out qty);

                    SortedList<string, object> list = new SortedList<string, object>();
                    list.Add("stepid", stepdr["StepID"].ToString());
                    list.Add("sequnce", i);
                    list.Add("toolid", toolID);
                    list.Add("qty", qty);
                    m_DAL.InsertWorkFlowStepTools(list);
                }
            }
        }

        private string CreateCutTool(DataRow tooldr)
        {
            string toolID = "";
            string cdoName = "CutTool";
            string cdoFieldName = "CutToolName";
            string cdoFieldID = "CutToolID";
            string name = tooldr["ToolName"].ToString();
            SyncParameterEntity inputParaEntity = new SyncParameterEntity();
            DataSet ds = m_DAL.GetNDOTable(cdoName, cdoFieldName, name);
            if (ds.Tables[0].Rows.Count > 0)
            {
                toolID = ds.Tables[0].Rows[0][cdoFieldID].ToString();

            }
            else
            {
                #region 属性赋值
                DataEntity entity = new DataEntity();
                entity.FieldName = "Name";
                entity.FieldType = "dataField";
                entity.FieldValue = name;
                inputParaEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "DrawingNo";
                entity.FieldType = "dataField";
                entity.FieldValue = tooldr["drawingNo"].ToString();
                inputParaEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "Description";
                entity.FieldType = "dataField";
                entity.FieldValue = tooldr["Description"].ToString();
                inputParaEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "Specification";
                entity.FieldType = "dataField";
                entity.FieldValue = tooldr["specNo"].ToString();
                inputParaEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "VendorSerialNumber";
                entity.FieldType = "dataField";
                entity.FieldValue = tooldr["standardNo"].ToString();
                inputParaEntity.DataList.Add(entity);
                #endregion

                entity = new DataEntity();
                entity.FieldName = "ResourceType";
                entity.FieldType = "namedObjectField";
                if (string.IsNullOrEmpty(tooldr["drawingNo"].ToString()))
                {
                    entity.FieldValue = "通用";
                }
                else
                {
                    entity.FieldValue = "专用";
                }

                inputParaEntity.DataList.Add(entity);

                OutInfoEntity infoEntity = new OutInfoEntity();
                ExecuteAPI exectAPI = new ExecuteAPI();
                exectAPI.CreateNDOEntity(cdoName, inputParaEntity, ref infoEntity);
                m_OutParameterObjectList.Add(infoEntity);
                if (infoEntity.OutFlag == 1)
                {
                    ds = m_DAL.GetNDOTable(cdoName, cdoFieldName, name);
                    toolID = ds.Tables[0].Rows[0][cdoFieldID].ToString();
                }
            }
            return toolID;
        }

        private string CreateMeasureTool(DataRow tooldr)
        {
            string toolID = "";
            string cdoName = "MeasureTool";
            string cdoFieldName = "MeasureToolName";
            string cdoFieldID = "MeasureToolID";
            string name = tooldr["ToolName"].ToString();
            SyncParameterEntity inputParaEntity = new SyncParameterEntity();
            DataSet ds = m_DAL.GetNDOTable(cdoName, cdoFieldName, name);
            if (ds.Tables[0].Rows.Count > 0)
            {
                toolID = ds.Tables[0].Rows[0][cdoFieldID].ToString();

            }
            else
            {
                #region 属性赋值
                DataEntity entity = new DataEntity();
                entity.FieldName = "Name";
                entity.FieldType = "dataField";
                entity.FieldValue = name;
                inputParaEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "DrawingNo";
                entity.FieldType = "dataField";
                entity.FieldValue = tooldr["drawingNo"].ToString();
                inputParaEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "Description";
                entity.FieldType = "dataField";
                entity.FieldValue = tooldr["Description"].ToString();
                inputParaEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "Specification";
                entity.FieldType = "dataField";
                entity.FieldValue = tooldr["specNo"].ToString();
                inputParaEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "VendorSerialNumber";
                entity.FieldType = "dataField";
                entity.FieldValue = tooldr["standardNo"].ToString();
                inputParaEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "MeasureRange";
                entity.FieldType = "dataField";
                entity.FieldValue = tooldr["range"].ToString();
                inputParaEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "MeasurePrecision";
                entity.FieldType = "dataField";
                entity.FieldValue = tooldr["precision"].ToString();
                inputParaEntity.DataList.Add(entity);
                #endregion

                entity = new DataEntity();
                entity.FieldName = "ResourceType";
                entity.FieldType = "namedObjectField";
                if (string.IsNullOrEmpty(tooldr["drawingNo"].ToString()))
                {
                    entity.FieldValue = "通用";
                }
                else
                {
                    entity.FieldValue = "专用";
                }

                inputParaEntity.DataList.Add(entity);

                OutInfoEntity infoEntity = new OutInfoEntity();
                ExecuteAPI exectAPI = new ExecuteAPI();
                exectAPI.CreateNDOEntity(cdoName, inputParaEntity, ref infoEntity);
                m_OutParameterObjectList.Add(infoEntity);
                if (infoEntity.OutFlag == 1)
                {
                    ds = m_DAL.GetNDOTable(cdoName, cdoFieldName, name);
                    toolID = ds.Tables[0].Rows[0][cdoFieldID].ToString();
                }
            }
            return toolID;
        }

        private string CreateSpecialTool(DataRow tooldr)
        {
            string toolID = "";
            string cdoName = "SpecialTool";
            string cdoFieldName = "SpecialToolName";
            string cdoFieldID = "SpecialToolID";
            string name = tooldr["ToolName"].ToString();
            SyncParameterEntity inputParaEntity = new SyncParameterEntity();
            DataSet ds = m_DAL.GetNDOTable(cdoName, cdoFieldName, name);
            if (ds.Tables[0].Rows.Count > 0)
            {
                toolID = ds.Tables[0].Rows[0][cdoFieldID].ToString();

            }
            else
            {
                #region 属性赋值
                DataEntity entity = new DataEntity();
                entity.FieldName = "Name";
                entity.FieldType = "dataField";
                entity.FieldValue = name;
                inputParaEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "DrawingNo";
                entity.FieldType = "dataField";
                entity.FieldValue = tooldr["drawingNo"].ToString();
                inputParaEntity.DataList.Add(entity);
                #endregion

                entity = new DataEntity();
                entity.FieldName = "ResourceType";
                entity.FieldType = "namedObjectField";
                if (string.IsNullOrEmpty(tooldr["drawingNo"].ToString()))
                {
                    entity.FieldValue = "通用";
                }
                else
                {
                    entity.FieldValue = "专用";
                }

                inputParaEntity.DataList.Add(entity);

                OutInfoEntity infoEntity = new OutInfoEntity();
                ExecuteAPI exectAPI = new ExecuteAPI();
                exectAPI.CreateNDOEntity(cdoName, inputParaEntity, ref infoEntity);
                m_OutParameterObjectList.Add(infoEntity);
                if (infoEntity.OutFlag == 1)
                {
                    ds = m_DAL.GetNDOTable(cdoName, cdoFieldName, name);
                    toolID = ds.Tables[0].Rows[0][cdoFieldID].ToString();
                }
            }
            return toolID;
        }

        /// <summary>
        /// WriteBy: YangSJ 2018-3-14
        /// 更新过站工序
        /// </summary>
        /// <param name="strWorkflowstepid"></param>
        /// <param name="manhours"></param>
        private void UpdateStepInfo(string strWorkflowstepid, string manhours, string controlcode)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(manhours))
                {
                    decimal decManhours = 0;
                    if (decimal.TryParse(manhours, out decManhours))
                    {//商品工时
                        m_DAL.UpdateStepManHoursInfo(strWorkflowstepid, decManhours);
                    }
                }
                if (!string.IsNullOrWhiteSpace(controlcode))
                {
                    //控制码
                    m_DAL.UpdateStepControlCodeInfo(strWorkflowstepid, controlcode);

                }
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex.Message, 0, "更新step");
            }
        }



        public void ShowAttribute()
        {

        }
    }
}
